//
//  FKConfirmOrderVC.m
//  HappyTest
//
//  Created by Macbook Pro on 2019/2/18.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKConfirmOrderVC.h"
#import "FKCustomBtn.h"
#import "FKConfirmOrderCell.h"
#import "FKAddAddressVC.h"
#import "FKChooseAddressVC.h"
#import "FKPayMethodView.h"
#import "FKPayResultVC.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h> // 微信支付
#import "FKPayPwdInputView.h"
#import "FKPayResultVC.h"
#import "FKSetPayPwdVC.h"
#import "FKChooseCouponPopView.h"

@interface FKConfirmOrderVC ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, weak) UILabel *countLabel;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSArray *goodsArray;

@property (nonatomic, weak) UILabel *nameLabel;
@property (nonatomic, weak) UILabel *mobileLabel;
@property (nonatomic, weak) UILabel *addressLabel;
@property (nonatomic, weak) UIButton *addBtn;

@property (nonatomic, weak) UILabel *freightLabel;
@property (nonatomic, weak) UITextField *nameField;
@property (nonatomic, weak) UITextField *discountField;
@property (nonatomic, weak) UITextField *contactMobileField;
@property (nonatomic, weak) UITextField *remarkField;
@property (nonatomic, weak) UILabel *commodityNumLabel;
@property (nonatomic, weak) UILabel *subtotalLabel;

@property (nonatomic, strong) FKPayMethodView *payMethodView;
@property (nonatomic, strong) FKPayPwdInputView *pwdView;
@property (nonatomic, strong) NSMutableDictionary *param;
@property(nonatomic,strong)NSDictionary *payInfoDict;//生成订单获取类型

@end

@implementation FKConfirmOrderVC
-(NSDictionary *)payInfoDict
{
    if (!_payInfoDict) {
        _payInfoDict = @{};
    }return _payInfoDict;
}
- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}

- (FKPayMethodView *)payMethodView
{
    if (!_payMethodView) {
        _payMethodView = [[FKPayMethodView alloc] init];
    }
    return _payMethodView;
}

- (FKPayPwdInputView *)pwdView
{
    if (!_pwdView) {
        _pwdView = [[FKPayPwdInputView alloc] init];
    }
    return _pwdView;
}

- (NSArray *)goodsArray
{
    if (!_goodsArray) {
        _goodsArray = [NSArray array];
    }
    return _goodsArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"确认下单";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payHandler:) name:@"alipay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payHandler:) name:@"wechatPay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAddress:) name:@"selectedAddressNoti" object:nil];
    
    // 底部
    UIView *bottomView = [[UIView alloc] init];
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = [UIColor whiteColor];
    
    UIButton *commitBtn = [UIButton fk_btnWithTarget:self action:@selector(commitBtnClicked) font:fk_adjustFont(16) normalTitle:@"立即下单" normalTitleColor:[UIColor whiteColor] selectedTitle:nil selectedTitleColor:nil normalImg:nil selectedImg:nil bgImg:[UIImage imageNamed:@"bg_main"] selectedBgImg:nil];
    [bottomView addSubview:commitBtn];
    
    UILabel *countLabel = [UILabel fk_labelWithFont:fk_adjustFont(15) textColor:fkPriceRed textAlignment:NSTextAlignmentRight];
    [bottomView addSubview:countLabel];
    self.countLabel = countLabel;
    
    UITableView *tableView  = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.height.mas_equalTo(fkTabBarH);
    }];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.offset(0);
        make.width.mas_equalTo(fk_adjustW(132));
    }];
    [countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.equalTo(commitBtn.mas_left).offset(-12);
        make.centerY.offset(0);
    }];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    // 头部：收货地
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(100))];
    header.backgroundColor = [UIColor whiteColor];

    UIView *addressView = [[UIView alloc] init];
    [header addSubview:addressView];
    [addressView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addressViewDidTap)]];

    UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"address_location"]];
    [header addSubview:iconView];

    UILabel *nameLabel = [UILabel fk_labelWithFont:fk_adjustFont(16) textColor:fkColor333333];
    [header addSubview:nameLabel];
    self.nameLabel = nameLabel;

    UILabel *mobileLabel = [UILabel fk_labelWithFont:fk_adjustFont(16) textColor:fkColor333333];
    [header addSubview:mobileLabel];
    self.mobileLabel = mobileLabel;

    UIImageView *arrowView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"address_add_arrow"]];
    [header addSubview:arrowView];

    UILabel *addressLabel = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333];
    [header addSubview:addressLabel];
    self.addressLabel = addressLabel;
    addressLabel.numberOfLines = 0;

    UIImageView *bottomLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"order_address_bg"]];
    [header addSubview:bottomLine];

    UIButton *addBtn = [UIButton fk_btnWithTarget:self action:@selector(addBtnClicked) img:[UIImage imageNamed:@"address_location"]];
    [header addSubview:addBtn];
    self.addBtn = addBtn;
    [addBtn setTitle:@"添加收货地址" forState:UIControlStateNormal];
    addBtn.titleLabel.font = fk_adjustFont(14);
    [addBtn setTitleColor:fkColor666666 forState:UIControlStateNormal];
    addBtn.backgroundColor = [UIColor whiteColor];
    addBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0);
    addBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    addBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);
    addBtn.hidden = true;
    
    NSDictionary *other_data = self.confirmDict[@"other_data"];
    if ([other_data[@"item_type"] isEqualToString:@"2"]) { // 物流商品
        tableView.tableHeaderView = header;
    }
//    tableView.tableHeaderView = header;
    
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.centerY.offset(0);
    }];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.height.mas_equalTo(3);
    }];
    [addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(bottomLine.mas_top);
    }];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(iconView.mas_right).offset(12);
        make.top.offset(fk_adjustW(15));
    }];
    [arrowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-12);
        make.centerY.offset(0);
    }];
    [mobileLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(arrowView.mas_left).offset(-12);
        make.centerY.equalTo(nameLabel);
    }];
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bottomLine.mas_top).offset(fk_adjustW(-15));
        make.left.equalTo(nameLabel);
        make.right.greaterThanOrEqualTo(mobileLabel);
    }];
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(bottomLine.mas_top);
    }];
    
    // footer
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(176) + 10)];
    footer.backgroundColor = [UIColor whiteColor];
    footer.clipsToBounds = true;
    
    UIView *discountView = [[UIView alloc] init];
    [footer addSubview:discountView];
    [discountView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(discountViewDidTap)]];
    
    UILabel *discountTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"优惠券"];
    [discountView addSubview:discountTitle];
    
    UITextField *discountField = [[UITextField alloc] init];
    [discountView addSubview:discountField];
    self.discountField = discountField;
    discountField.font = fk_adjustFont(14);
    discountField.textColor = fkColor333333;
    discountField.textAlignment = NSTextAlignmentRight;
    discountField.userInteractionEnabled = false;
    
    UIImageView *arrowView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"address_add_arrow"]];
    [discountView addSubview:arrowView2];
    
    UIView *line1 = [UIView fk_lineWithFrame:CGRectMake(12, fk_adjustW(44), fkScreenW - 24, 0.8)];
    [footer addSubview:line1];
    
    UILabel *freightTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"运费"];
    [footer addSubview:freightTitle];
    
    UILabel *freightLabel = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 textAlignment:NSTextAlignmentRight];
    [footer addSubview:freightLabel];
    self.freightLabel = freightLabel;
    
    UILabel *nameTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"姓名:"];
    [footer addSubview:nameTitle];
    
    UITextField *nameField = [[UITextField alloc] init];
    [footer addSubview:nameField];
    self.nameField = nameField;
    nameField.delegate = self;
    nameField.font = fk_adjustFont(14);
    nameField.textColor = fkColor333333;
    nameField.textAlignment = NSTextAlignmentRight;
    nameField.placeholder = @"请填写姓名";
    
    UIView *line2 = [UIView fk_lineWithFrame:CGRectMake(12, fk_adjustW(88), fkScreenW - 24, 0.8)];
    [footer addSubview:line2];
    
    UILabel *contactMobileTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"联系方式:"];
    [footer addSubview:contactMobileTitle];
    
    UITextField *contactMobileField = [[UITextField alloc] init];
    [footer addSubview:contactMobileField];
    self.contactMobileField = contactMobileField;
    contactMobileField.delegate = self;
    contactMobileField.font = fk_adjustFont(14);
    contactMobileField.textColor = fkColor333333;
    contactMobileField.textAlignment = NSTextAlignmentRight;
    contactMobileField.placeholder = @"请填写联系方式";
    contactMobileField.keyboardType = UIKeyboardTypeNumberPad;
    
    UILabel *remarkTitle = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"备注:"];
    [footer addSubview:remarkTitle];
    
    UITextField *remarkField = [[UITextField alloc] init];
    [footer addSubview:remarkField];
    self.remarkField = remarkField;
    remarkField.font = fk_adjustFont(14);
    remarkField.textColor = fkColor333333;
    remarkField.textAlignment = NSTextAlignmentRight;
    remarkField.placeholder = @"给卖家留言（选填）";
    
    UIView *line3 = [UIView fk_lineWithFrame:CGRectMake(12, fk_adjustW(132), fkScreenW - 24, 0.8)];
    [footer addSubview:line3];
    
    UIView *line4 = [UIView fk_lineWithFrame:CGRectMake(12, fk_adjustW(176), fkScreenW - 24, 0.8)];
    [footer addSubview:line4];
    
    UILabel *commodityNumLabel = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 textAlignment:NSTextAlignmentRight];
    [footer addSubview:commodityNumLabel];
    self.commodityNumLabel = commodityNumLabel;
    
    UILabel *subtotalLabel = [UILabel fk_labelWithFont:fk_adjustFont(15) textColor:fkPriceRed textAlignment:NSTextAlignmentRight];
    [footer addSubview:subtotalLabel];
    self.subtotalLabel = subtotalLabel;
    
    UIView *separator = [UIView fk_lineWithFrame:CGRectMake(0, fk_adjustW(176), fkScreenW, 10)];
    [footer addSubview:separator];
    
    tableView.tableFooterView = footer;
    
    if ([other_data[@"item_type"] isEqualToString:@"1"]) { // 核销商品
        [discountView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.top.offset(0);
            make.bottom.equalTo(line1.mas_top);
        }];
        [discountTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12);
            make.top.bottom.offset(0);
        }];
        [arrowView2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-12);
            make.centerY.equalTo(discountTitle);
        }];
        [discountField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(arrowView2.mas_left).offset(-10);
            make.centerY.equalTo(discountTitle);
        }];
        freightTitle.hidden = true;
        freightLabel.hidden = true;
        [nameTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12);
            make.top.equalTo(line1.mas_bottom);
            make.bottom.equalTo(line2.mas_top);
        }];
        [nameField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-12);
            make.width.offset(260);
            make.top.bottom.equalTo(nameTitle);
        }];
        [contactMobileTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(nameTitle);
            make.top.equalTo(line2.mas_bottom);
            make.bottom.equalTo(line3.mas_top);
        }];
        [contactMobileField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(nameField);
            make.width.equalTo(nameField);
            make.top.bottom.equalTo(contactMobileTitle);
        }];
        [remarkTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(discountTitle);
            make.top.equalTo(line3.mas_bottom);
            make.bottom.equalTo(line4.mas_top);
        }];
        [remarkField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(nameField);
            make.top.bottom.equalTo(remarkTitle);
            make.left.lessThanOrEqualTo(remarkTitle.mas_right).offset(10);
        }];
        [subtotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(freightLabel);
            make.top.equalTo(line3.mas_bottom);
            make.bottom.equalTo(separator.mas_top);
        }];
        [commodityNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(subtotalLabel.mas_left).offset(-10);
            make.centerY.equalTo(subtotalLabel);
        }];
    } else { // 物流商品
        nameTitle.hidden = true;
        nameField.hidden = true;
        contactMobileTitle.hidden = true;
        contactMobileField.hidden = true;
        [discountView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.top.offset(0);
            make.bottom.equalTo(line1.mas_top);
        }];
        [discountTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12);
            make.top.bottom.offset(0);
        }];
        [arrowView2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-12);
            make.centerY.equalTo(discountTitle);
        }];
        [discountField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(arrowView2.mas_left).offset(-10);
            make.centerY.equalTo(discountTitle);
        }];
        [freightTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12);
            make.top.equalTo(line1.mas_bottom);
            make.bottom.equalTo(line2.mas_top);
        }];
        [freightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-12);
            make.centerY.equalTo(freightTitle);
        }];
        [remarkTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(freightTitle);
            make.top.equalTo(line2.mas_bottom);
            make.bottom.equalTo(line3.mas_top);
        }];
        [remarkField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(freightLabel);
            make.top.bottom.equalTo(remarkTitle);
            make.width.offset(260);
        }];
        [subtotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(freightLabel);
            make.top.equalTo(line3.mas_bottom);
            make.bottom.equalTo(separator.mas_top);
        }];
        [commodityNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(subtotalLabel.mas_left).offset(-10);
            make.centerY.equalTo(subtotalLabel);
        }];
    }
    
    [self setupData];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)payHandler:(NSNotification *)noti
{
    FKPayResultVC *vc = [[FKPayResultVC alloc] init];
    vc.needRemoveBeforeVc = true;
    vc.payInfoDict = self.payInfoDict;
    vc.failure = ![noti.userInfo[@"success"] boolValue];
    fkPushNav(vc);
}

- (void)setupData
{
    NSArray *list = self.confirmDict[@"goods"];
    self.goodsArray = list;
    
    NSDictionary *address = self.confirmDict[@"address"];
    if (address.count > 0) {
        self.nameLabel.text = address[@"receiver"];
        self.mobileLabel.text = address[@"mobile"];
        self.addressLabel.text = address[@"address"];
        self.param[@"address_id"] = address[@"id"];
    } else {
        self.addBtn.hidden = false;
    }
    
    NSDictionary *other_data = self.confirmDict[@"other_data"];
    self.countLabel.text = fkFORMAT(@"合计: ￥%@", other_data[@"total_price"]);
    self.countLabel.attributedText = [self.countLabel.text fk_addAttributeStyle:@"合计:" color:fkColor333333 font:fk_adjustFont(14)];
    
    self.freightLabel.text = fkFORMAT(@"￥%@", other_data[@"freight"]);
    NSArray *coupon = self.confirmDict[@"coupon"];
    if (coupon.count == 0) {
        self.discountField.placeholder = @"无可用优惠券";
    } else {
        self.discountField.placeholder = fkFORMAT(@"可用优惠券%zd张", coupon.count);
    }
    self.commodityNumLabel.text = fkFORMAT(@"共%@件商品", other_data[@"total_num"]);
    self.subtotalLabel.text = fkFORMAT(@"小计: ￥%@", other_data[@"total_price"]);
    self.subtotalLabel.attributedText = [self.subtotalLabel.text fk_addAttributeStyle:@"小计:" color:fkColor333333 font:fk_adjustFont(14)];
    
    NSDictionary *contactInfo = self.confirmDict[@"contact_info"];
    if (contactInfo.count > 0) {
        self.nameField.text = contactInfo[@"contact_name"];
        self.contactMobileField.text = contactInfo[@"contact_mobile"];
//        [self.nameField becomeFirstResponder];
    }
    
    // 设置参数
    self.param[@"item_id"] = self.confirmDict[@"item_id"];
    self.param[@"sku_id"] = self.confirmDict[@"sku_id"];
    self.param[@"num"] = self.confirmDict[@"num"];
    self.param[@"is_set_meal"] = self.confirmDict[@"is_set_meal"];
    
    [self.tableView reloadData];
}

- (void)updateAddress:(NSNotification *)noti
{
    NSDictionary *dict = noti.userInfo;
    NSDictionary *address = dict[@"address"];
    
    self.nameLabel.text = address[@"shperson"];
    self.mobileLabel.text = address[@"mobile"];
    self.addressLabel.text = fkFORMAT(@"%@%@%@%@", address[@"province"], address[@"city"], address[@"county"], address[@"detail_info"]);
    self.param[@"address_id"] = address[@"id"];
    self.addBtn.hidden = true;
}

- (void)addressViewDidTap
{
    FKChooseAddressVC *vc = [[FKChooseAddressVC alloc] init];
    if (self.confirmDict[@"address"]) {
        vc.addressId = self.confirmDict[@"address"][@"id"];
    }
    fkPushNav(vc);
    fkWeakSelf(self);
    vc.selectedAddressBlock = ^(NSDictionary * _Nonnull address) {
        __strong typeof(weakself) strongSelf = weakself;
        strongSelf.param[@"address_id"] = address[@"id"];
    };
}

- (void)addBtnClicked
{
    FKAddAddressVC *vc = [[FKAddAddressVC alloc] init];
    vc.chooseAddress = true;
    fkPushNav(vc);
}

- (void)commitBtnClicked
{
    [self.view endEditing:true];
    

    
    NSDictionary *other_data = self.confirmDict[@"other_data"];
    if ([other_data[@"item_type"] isEqualToString:@"1"]) { // 核销商品
        if (self.nameField.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:self.nameField.placeholder];
            return;
        }
        if (self.contactMobileField.text.length == 0) {
            [SVProgressHUD showInfoWithStatus:self.contactMobileField.placeholder];
            return;
        }
        if (self.contactMobileField.text.length != 11) {
            [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
            return;
        }

        self.param[@"contact_name"] = self.nameField.text;
        self.param[@"contact_mobile"] = self.contactMobileField.text;
    } else { // 物流商品
        if (!self.param[@"address_id"]) {
            [SVProgressHUD showInfoWithStatus:@"请选择收货地址"];
            return;
        }
    }

    [self getOrder];
}

- (void)discountViewDidTap
{
    NSArray *coupon = self.confirmDict[@"coupon"];
    if (coupon.count > 0) {
        FKChooseCouponPopView *view = [[FKChooseCouponPopView alloc] init];
        NSMutableArray *datas = [NSMutableArray arrayWithArray:coupon];
        [datas insertObject:@{@"id" : @""} atIndex:0];
        view.datas = datas;
        [view show];
        fkWeakSelf(self);
        view.chooseCouponBlock = ^(NSDictionary * _Nonnull data) {
            weakself.param[@"coupon_id"] = data[@"id"];
            
            weakself.discountField.text = data[@"price"] ? fkFORMAT(@"%@元优惠券", data[@"price"]) : @"";
            NSDictionary *other_data = weakself.confirmDict[@"other_data"];
            double totalPrice = [other_data[@"total_price"] doubleValue] - [data[@"price"] doubleValue];
            weakself.subtotalLabel.text = fkFORMAT(@"小计: ￥%.2f", totalPrice);
            weakself.subtotalLabel.attributedText = [weakself.subtotalLabel.text fk_addAttributeStyle:@"小计:" color:fkColor333333 font:fk_adjustFont(14)];
            weakself.countLabel.text = fkFORMAT(@"合计: ￥%.2f", totalPrice);
            weakself.countLabel.attributedText = [weakself.countLabel.text fk_addAttributeStyle:@"合计:" color:fkColor333333 font:fk_adjustFont(14)];
        };
    } else {
        [SVProgressHUD showInfoWithStatus:@"无可用优惠券"];
    }
    
    
//    FKChooseCouponVC *vc = [[FKChooseCouponVC alloc] init];
//    vc.payMoney = self.confirmDict[@"totalprice"];
//    vc.cate_id = @"0";
//    fkPushNav(vc);
//
//    fkWeakSelf(self);
//    vc.chooseCouponBlock = ^(FKCoupon * _Nonnull coupon) {
//        NSString *discount = fkFORMAT(@"-￥%@", coupon.money);
//        weakself.discountField.attributedText = [discount fk_addAttr:fkPriceRed font:fk_adjustFont(14)];
//
//        double totalPrice = [weakself.confirmDict[@"totalprice"] doubleValue];
//        double discountPrice = [coupon.money doubleValue];
//        double price = totalPrice - discountPrice;
//        weakself.countLabel.text = fkFORMAT(@"合计: ￥%.2f", price);
//        weakself.countLabel.attributedText = [weakself.countLabel.text fk_addAttributeStyle:@"合计:" color:fkColor333333 font:fk_adjustFont(14)];
//        weakself.param[@"coupon_id"] = coupon.id;
//    };
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.goodsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKConfirmOrderCell *cell = [FKConfirmOrderCell cellWith:tableView];
    cell.data = self.goodsArray[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    if (!header) {
        header = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"header"];
        header.contentView.backgroundColor = [UIColor whiteColor];
        
        UIView *separator = [UIView fk_lineWithFrame:CGRectMake(0, 0, fkScreenW, 10)];
        [header.contentView addSubview:separator];
        
        UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"order_icon_listing"]];
        [header.contentView addSubview:iconView];
        
        UILabel *titleLabel = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333 text:@"订单信息"];
        [header.contentView addSubview:titleLabel];
        
        UIView *separator1 = [[UIView alloc] init];
        [header.contentView addSubview:separator1];
        separator1.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12);
            make.centerY.offset(5);
        }];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(iconView.mas_right).offset(8);
            make.centerY.equalTo(iconView);
        }];
        [separator1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.offset(0);
            make.height.offset(0.8);
        }];
    }
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
//    FKConfirmOrderFooter *footer = [FKConfirmOrderFooter sectionView:tableView];
//    footer.data = self.confirmDict;
//    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return fk_adjustW(120);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return fk_adjustW(50) + 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
//    return fk_adjustW(176) + 10;
    return 0.01;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.payMethodView) {
        [self.payMethodView showAgain];
    }
    if (self.pwdView) {
        [self.pwdView showAgain];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *finalText = [textField.text stringByAppendingString:string];
    if ([textField isEqual:self.nameField]) {
        return finalText.length <= 12;
    } else if ([textField isEqual:self.contactMobileField]) {
        return finalText.length <= 11;
    }
    return true;
}

#pragma mark - 网络请求
- (void)getOrder
{
    self.param[@"remark"] = self.remarkField.text;
    self.param[@"goods"] = self.orderParam;
    self.param[@"cart_ids"] = self.cartIds;
    [SVProgressHUD show];
    [FKHttpTool postWithSuffix:@"m=Home&c=Orders&a=store" param:self.param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD dismiss];
            // 弹出选择支付方式
            self.payMethodView.amount = result.data[@"pay_amount"];
            self.payInfoDict = result.data[@"jump_item_activity"];
            [self.payMethodView show];
            fkWeakSelf(self);
            self.payMethodView.selectePayMethodBlock = ^(NSString * _Nonnull payType) {
                if ([payType isEqualToString:@"balance"]) { // 余额支付
                    if ([FKCacheTool isHasPayPwd]) { // 设置了支付密码
                        [weakself.payMethodView dismiss];
//                        FKPayPwdInputView *pwdView = [[FKPayPwdInputView alloc] init];
                        [weakself.pwdView show];
                        weakself.pwdView.superVC = weakself;
                        weakself.pwdView.inputFinishBlock = ^(NSString *pwd) {
                            NSMutableDictionary *param = [NSMutableDictionary dictionary];
                            param[@"payment"] = payType;
                            param[@"order_sn"] = result.data[@"order_sn"];
                            param[@"password"] = pwd;
                            [weakself orderPay:param];
                            // 刷新购物车的数量
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCartList" object:nil];
                        };
                        weakself.pwdView.closeBlock = ^{
                            [weakself enterPayFailureResult];
                        };
                    } else { // 没有设置支付密码
                        [weakself.payMethodView hide];
                        FKSetPayPwdVC *vc = [[FKSetPayPwdVC alloc] init];
                        [weakself.navigationController pushViewController:vc animated:true];
                    }
                } else {
                    [weakself.payMethodView dismiss];
                    NSMutableDictionary *param = [NSMutableDictionary dictionary];
                    param[@"payment"] = payType;
                    param[@"order_sn"] = result.data[@"order_sn"];
                    param[@"trade_type"] = @"APP";
                    [weakself orderPay:param];
                }
            };
            self.payMethodView.closeBlock = ^{
                [weakself enterPayFailureResult];
            };
        }
    } failure:nil];
}

- (void)orderPay:(NSDictionary *)param
{
    [FKHttpTool postWithSuffix:@"m=Home&c=Payment&a=pay" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            // 拉起微信或者支付宝
            NSString *payType = param[@"payment"];
            if ([payType isEqualToString:@"wechat"]) {
                PayReq *req = [[PayReq alloc] init];
                req.partnerId = result.data[@"partnerid"];
                req.prepayId = result.data[@"prepayid"];
                req.nonceStr = result.data[@"noncestr"];
                req.timeStamp = [result.data[@"timestamp"] intValue];
                req.package = result.data[@"package"];
                req.sign = result.data[@"sign"];
                [WXApi sendReq:req];
            } else if ([payType isEqualToString:@"alipay"]) {
                NSString *str = result.data[@"pay_info"];
                // NOTE: 调用支付结果开始支付
                NSString *scheme = [NSBundle mainBundle].bundleIdentifier; // 我自己直接用bundleID作为scheme了
                [[AlipaySDK defaultService] payOrder:str fromScheme:scheme callback:nil];
            } else {
                FKPayResultVC *vc = [[FKPayResultVC alloc] init];
                vc.needRemoveBeforeVc = true;
                NSDictionary *other_data = self.confirmDict[@"other_data"];
                vc.type = other_data[@"item_type"];
                [self.navigationController pushViewController:vc animated:true];
            }
        } else {
            [self enterPayFailureResult];
        }
    } failure:^(NSError *error) {
        [self enterPayFailureResult];
    }];
}

- (void)enterPayFailureResult
{
    // 刷新购物车的数量
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCartList" object:nil];
    
    FKPayResultVC *vc = [[FKPayResultVC alloc] init];
    vc.needRemoveBeforeVc = true;
    vc.failure = true;
    NSDictionary *other_data = self.confirmDict[@"other_data"];
    vc.type = other_data[@"item_type"];
    [self.navigationController pushViewController:vc animated:true];
}


@end
